<template>
  <cs-card>
    <el-tabs v-model="tabActiveName" @tab-click="handleTabClick">
      <el-tab-pane label="车辆列表" name="2" class="el-tab-first">
        <el-table
          v-loading="isLoading"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="num" label="车牌号码"> </el-table-column>
          <el-table-column prop="zs" label="轴数" width="60"> </el-table-column>
          <el-table-column prop="name" label="车辆联系人" width="120">
            <template v-slot="scoped">
              {{ scoped.row.name ? scoped.row.name : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="color" label="车辆颜色" width="120">
            <template v-slot="scoped">
              {{ scoped.row.color ? scoped.row.color : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="phoneNum" label="手机号" width="180">
            <template v-slot="scoped">
              {{ scoped.row.phoneNum ? scoped.row.phoneNum : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="车辆类型" width="180">
            <template v-slot="scoped">
              {{ scoped.row.type ? scoped.row.type : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="validityTime" label="证件有效期" width="180">
            <template v-slot="scoped">
              {{ scoped.row.validityTime ? scoped.row.validityTime : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="companyName" label="所属企业">
            <template v-slot="scoped">
              {{ scoped.row.companyName ? scoped.row.companyName : '—' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="190">
            <template v-slot="scoped">
              <el-link type="primary" class="details" @click="cartDetailVisible(scoped.row.num)"
                >详情</el-link
              >
              <el-link
                v-if="innerMenu.upd.flag"
                type="primary"
                @click="alterCartDialogVisible(scoped.row)"
                >编辑</el-link
              >
              <el-link
                v-if="innerMenu.upd.flag"
                type="primary"
                @click="setBlackNameBtnClick(scoped.row.id, scoped.row.num)"
                class="setBlackNameLink"
                >设置黑名单</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="黑名单" name="1">
        <el-table
          v-loading="isLoading"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="num" label="车牌号码"> </el-table-column>
          <el-table-column prop="zs" label="轴数" width="60"> </el-table-column>
          <el-table-column prop="name" label="车辆联系人" width="120">
            <template v-slot="scoped">
              {{ scoped.row.name ? scoped.row.name : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="color" label="车辆颜色" width="120">
            <template v-slot="scoped">
              {{ scoped.row.color ? scoped.row.color : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="phoneNum" label="手机号" width="180">
            <template v-slot="scoped">
              {{ scoped.row.phoneNum ? scoped.row.phoneNum : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="车辆类型" width="180">
            <template v-slot="scoped">
              {{ scoped.row.type ? scoped.row.type : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="validityTime" label="证件有效期" width="180">
            <template v-slot="scoped">
              {{ scoped.row.validityTime ? scoped.row.validityTime : '—' }}
            </template>
          </el-table-column>
          <el-table-column prop="companyName" label="所属企业">
            <template v-slot="scoped">
              {{ scoped.row.companyName ? scoped.row.companyName : '—' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="190" fixed="right">
            <template v-slot="scoped">
              <!-- <el-link type="primary" class="details" @click="cartDetailVisible(scoped.row.num)"
                >详情</el-link
              >
              <el-link type="primary" @click="alterCartDialogVisible(scoped.row)">编辑</el-link> -->
              <el-link type="primary" @click="setBlackNameBtnClick(scoped.row.id, scoped.row.num)"
                >移出黑名单</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <div id="pagination_section">
      <span class="currentSelect">{{ `已选${currentSelect}项，共${totalCount}项` }}</span>
      <div class="pagination_right">
        <span>{{ `${pageSize}条/页` }}</span>
        <cs-pagination
          :currentPage="currentPage"
          :totalPage="totalPage"
          @firstPageClick="firstPageClick"
          @previousPageClick="previousPageClick"
          @nextPageClick="nextPageClick"
          @lastPageClick="lastPageClick"
          @junkToOtherPage="junkToOtherPage"
        />
      </div>
    </div>
  </cs-card>
</template>

<script>
import csCard from '@/components/cs-card/cs-card.vue'
import csPagination from '@/components/cs-pagination/cs-pagination.vue'
import {
  getCarInfo,
  setCarBlackName,
  exportlistcar,
  getTemplate
} from '@/service/operate/cart_manage/cart_manage'

export default {
  components: {
    csCard,
    csPagination
  },
  props: {
    innerMenu: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      tableData: [],
      carBlackNameTableData: [],
      // 当前页码
      currentPage: 1,
      // 一页的条数
      pageSize: 10,
      // 总共多少条数据
      totalCount: 0,
      // 总共多少页
      totalPage: 0,
      currentSelect: 0,
      selectId: [],
      vehicleUser: '',
      vehicleNumber: '',
      vehicleType: '',
      isBlack: '2',
      // 标签选项
      tabActiveName: '2',
      isLoading: true
    }
  },
  created() {
    this.getCarInfo(this.currentPage, this.pageSize, this.tabActiveName)
    // 发送当前选择的数量
    this.$bus.$emit('currentSelect_car', this.currentSelect)
    // 编辑车辆成功后重新请求表格数据
    this.$bus.$on('editCatSuccess', () => {
      this.getCarInfo(this.currentPage, this.pageSize, this.tabActiveName)
    })
    // 添加车辆成功后重新请求表格数据
    this.$bus.$on('addCatSuccess', () => {
      this.getCarInfo(this.currentPage, this.pageSize, this.tabActiveName)
    })
    // 删除车辆成功后重新请求表格数据
    this.$bus.$on('delCatSuccess', () => {
      this.getCarInfo(this.currentPage, this.pageSize, this.tabActiveName)
    })
    // 查询车辆事件
    this.$bus.$on('searchCar', (res) => {
      if (this.isLoading) return
      const { carContacts, carNum } = res
      this.vehicleUser = carContacts
      this.vehicleNumber = carNum
      // this.vehicleType = carTypeValue
      console.log(this.tabActiveName)
      this.getCarInfo(1, this.pageSize, this.tabActiveName)
    })
    // 导出
    this.$bus.$on('carexportlist', (res) => {
      const { carContacts, carNum } = res
      this.vehicleUser = carContacts
      this.vehicleNumber = carNum
      // this.vehicleType = carTypeValue
      this.getExportlist({
        vehicleUser: this.vehicleUser,
        vehicleNumber: this.vehicleNumber,
        isBlack: this.isBlack
        // vehicleType: this.vehicleType
      })
    })
    this.$bus.$on('getTemplates', (res) => {
      this.getTemplates()
    })
  },
  beforeDestroy() {
    this.$bus.$off('carexportlist')
    this.$bus.$off('currentSelect_car')
    this.$bus.$off('cartDetailVisible')
    this.$bus.$off('alterCartDialogVisible')
    this.$bus.$off('emitCatDelID')
  },
  methods: {
    async getTemplates() {
      const data = await getTemplate()
      console.log('车辆信息导入模版', data)
      const filename = '车辆信息导入模版.xlsx'
      const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
        window.navigator.msSaveBlob(blob, decodeURI(filename))
      } else {
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob)
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', decodeURI(filename))
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
      }
    },
    async getExportlist(info) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const data = await exportlistcar(info)
      if (!!data) {
        const filename = '车辆信息表.xlsx'
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(filename))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(filename))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
        setTimeout(() => {
          loading.close()
        }, 2000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 2000)
      }
    },
    handleTabClick(tab, event) {
      if (this.tabActiveName === this.isBlack) return
      if (tab.index === '0') {
        this.isBlack = '2'
      } else {
        this.isBlack = '1'
      }

      this.currentPage = 1
      this.totalCount = 0
      this.totalPage = 0
      this.getCarInfo(1, 10, this.tabActiveName)
    },
    cartDetailVisible(carNumber) {
      this.$bus.$emit('cartDetailVisible', carNumber)
    },
    alterCartDialogVisible(row) {
      this.$bus.$emit('alterCartDialogVisible', row)
    },
    // 设置黑名单按钮点击事件
    setBlackNameBtnClick(id, carNumber) {
      console.log({ id, carNumber })
      this.isLoading = true
      if (this.tabActiveName === '2') {
        this.$confirm('确定要把该车辆设为黑名单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            try {
              const data = await setCarBlackName({
                id,
                carNumber,
                isBlackName: true
              })

              console.log(data)
              if (data.code === 0) {
                this.getCarInfo(this.currentPage, this.pageSize, this.tabActiveName)
                this.$message({
                  type: 'success',
                  message: '设置成功!'
                })
                this.isLoading = false
              } else {
                this.$message.error('设置黑名单失败')
                this.isLoading = false
              }
            } catch (err) {
              console.log(err)
              this.$message.error('设置黑名单失败')
              this.isLoading = false
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消选择'
            })
            this.isLoading = false
          })
      } else {
        this.$confirm('确定要把该车辆移出黑名单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            try {
              const data = await setCarBlackName({
                id,
                carNumber,
                isBlackName: false
              })
              console.log(data)
              if (data.code === 0) {
                this.getCarInfo(this.currentPage, this.pageSize, this.tabActiveName)
                this.$message({
                  type: 'success',
                  message: '设置成功!'
                })
                this.isLoading = false
              } else {
                this.$message.error('移出黑名单失败')
                this.isLoading = false
              }
            } catch (err) {
              console.log(err)
              this.$message.error('移出黑名单失败')
              this.isLoading = false
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消选择'
            })
            this.isLoading = false
          })
      }
    },
    // 获取表格信息
    async getCarInfo(
      pageNum = 1,
      pageSize = 10,
      isBlack = '2',
      vehicleUser = this.vehicleUser,
      vehicleNumber = this.vehicleNumber,
      vehicleType = this.vehicleType
    ) {
      this.isLoading = true
      try {
        const { code, data } = await getCarInfo({
          pageNum,
          pageSize,
          isBlack,
          vehicleUser,
          vehicleNumber,
          vehicleType
        })

        if (code === 0) {
          const carTabelData = data
          this.tableData = []
          carTabelData.list.forEach((item) => {
            this.tableData.push({
              id: item.id,
              // 车辆联系人
              name: item.contactsName,
              contactsPhone: item.contactsPhone,
              contactsIdCard: item.contactsIdCard,
              // 车牌号
              num: item.vehicleNumber,
              // 车辆颜色
              color: item.color,
              // 手机号
              phoneNum: item.contactsPhone,
              // 车辆类型
              type: item.vehicleType,
              // 有效期
              validityTime: item.expireDate,
              // 荷载
              loadCapacity: item.loadCapacity,
              // 轴数
              zs: item.axleCount,
              // 所属企业
              companyName: item.companyName,
              // 车辆状态
              state: item.state,
              remark: item.remark
            })
          })
          // 当前页码
          this.currentPage = carTabelData.currPage
          // 一页的条数
          this.pageSize = carTabelData.pageSize
          this.totalCount = carTabelData.totalCount
          this.totalPage = carTabelData.totalPage

          this.isLoading = false
        }
      } catch (err) {
        console.log(err)
        this.$message.error('服务器出错了')
      }
    },
    // 第一页
    firstPageClick() {
      if (this.isLoading) return
      this.getCarInfo(1, this.pageSize, this.tabActiveName)
    },
    // 上一页
    previousPageClick() {
      if (this.isLoading) return
      this.getCarInfo(this.currentPage - 1, this.pageSize, this.tabActiveName)
    },
    // 下一页
    nextPageClick() {
      if (this.isLoading) return
      this.getCarInfo(this.currentPage + 1, this.pageSize, this.tabActiveName)
    },
    // 最后一页
    lastPageClick() {
      if (this.isLoading) return
      this.getCarInfo(this.totalPage, this.pageSize, this.tabActiveName)
    },
    // 跳转页
    junkToOtherPage(page) {
      this.getCarInfo(page, this.pageSize, this.tabActiveName)
    },
    // 表格选择项变化时触发事件
    selectionChange(selection) {
      this.selectId = []
      // 获取当前选择多少项
      this.currentSelect = selection.length
      // 发送当前选择的数量
      this.$bus.$emit('currentSelect_car', this.currentSelect)
      selection.forEach((item) => {
        this.selectId.push(item.id)
      })
      this.$bus.$emit('emitCatDelID', this.selectId)
    }
  }
}
</script>

<style scoped>
.el-form-item >>> .el-form-item__label {
  color: #888888;
}

.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.form-select {
  width: 100%;
}

/* 表格选择框样式start */
.el-table >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.el-table >>> .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
}

.el-table >>> .el-checkbox__inner::before {
  top: 8px;
}
/* 表格选择框样式end */

.el-form-item >>> .el-form-item__label {
  padding: 0;
  padding-right: 46px;
}

.el-tabs >>> .is-top:nth-child(2) {
  margin-left: 20px;
}

.el-tabs >>> .el-tabs__active-bar {
  left: 20px;
}

.el-tabs >>> .el-tabs__active-bar {
  background-color: #006eff;
}

.el-tabs >>> .el-tabs__item.is-active {
  color: #006eff;
}

.el-tabs >>> .el-tabs__item {
  color: rgba(0, 110, 255, 0.5);
}

.setBlackNameLink {
  margin-left: 16px;
}
</style>
